#include "stm32f10x.h"

void Timer_Init(void)
{
    // init APB1 clock 
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    // select clock input mode, if you select extrnal input clock,must configure it
    TIM_InternalClockConfig(TIM2);

    // configure base-clock unit,such as prescaler psc, cnt,arr (auto reload register)
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitParam;
    // todo what's mean?
    TIM_TimeBaseInitParam.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitParam.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitParam.TIM_Period = 10000-1;
    TIM_TimeBaseInitParam.TIM_Prescaler = 7200 - 1; // 72 * 1000 * 1000
    TIM_TimeBaseInitParam.TIM_RepetitionCounter = 0;

    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitParam);


    // configure interrupt control
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
    TIM_ClearFlag(TIM2, TIM_IT_Update);

    // configure nvic,interrupt priority group
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

    // init nivc ,enable rcc(defult enabled by cpu)
    NVIC_InitTypeDef NVIC_InitParam;
    NVIC_InitParam.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitParam.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitParam.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitParam.NVIC_IRQChannelSubPriority = 1;
    NVIC_Init(&NVIC_InitParam);
    // start tim 
    TIM_Cmd(TIM2, ENABLE);

}

void External_Timer_Init(void)
{
    // enable rcc apb1
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    // select input clock mode
    TIM_ETRClockMode2Config(TIM2, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0);
    // init gpio for external clock input pa0 -> tim1_etr

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    GPIO_InitTypeDef GPIO_InitParam;
    GPIO_InitParam.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitParam.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitParam.GPIO_Speed = GPIO_Speed_50MHz; 
    GPIO_Init(GPIOA, &GPIO_InitParam);

    // init base-time unit
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitParam;
    TIM_TimeBaseInitParam.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitParam.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitParam.TIM_Period = 10-1;
    TIM_TimeBaseInitParam.TIM_Prescaler = 1-1;
    TIM_TimeBaseInitParam.TIM_RepetitionCounter = 0;

    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitParam);

    // configure TIM Interrupt
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);

    TIM_ClearFlag(TIM2, TIM_IT_Update);

    // configure interrupt priority group
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

    // init nvic
    NVIC_InitTypeDef NVIC_InitParam;
    NVIC_InitParam.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitParam.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitParam.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitParam.NVIC_IRQChannelSubPriority = 1;
    NVIC_Init(&NVIC_InitParam);

    // enable clock control
    TIM_Cmd(TIM2, ENABLE);
}
